import classnames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import Icon from '../Icon'
import styles from './index.module.scss'

type Props = {
  src: string
  className?: string
  alt?: string
}
/**
 * 拥有懒加载特性的图片组件
 * @param {String} props.src 图片地址
 * @param {String} props.className 样式类
 */
const Image = ({ src, className }: Props) => {
  // 对图片元素的引用
  const imgRef = useRef<HTMLImageElement>(null)
  const [error, setError] = useState(false)
  const [loading, setLoading] = useState(true)
  useEffect(() => {
    const img = imgRef.current!
    // 创建 观察
    const observer = new IntersectionObserver(function ([{ isIntersecting }]) {
      //如果在可视区
      if (isIntersecting) {
        // 设置 给真正的src 属性
        img.src = img.getAttribute('data-src')!
        // 关闭观察
        observer.unobserve(img)
      }
    })
    // 监控
    observer.observe(img)
    return () => {
      observer.unobserve(img)
    }
  }, [])
  return (
    <div className={classnames(styles.root, className)}>
      {/* 正在加载时显示的内容 */}
      {loading && (
        <div className="image-icon">
          <Icon type="iconphoto" />
        </div>
      )}

      {/* 加载出错时显示的内容 */}
      {error && (
        <div className="image-icon">
          <Icon type="iconphoto-fail" />
        </div>
      )}

      {/* 加载成功时显示的内容 */}
      <img
        alt=""
        data-src={src}
        ref={imgRef}
        onError={() => setError(true)}
        onLoad={() => setLoading(false)}
      />
    </div>
  )
}

export default Image
